/**
 * 数据保存工具脚本
 */
const fs = require('fs');
const path = require('path');
const csv = require('csv-parser');
const DEFAULT_CONFIG_PATH = './config/config.json';
const Sequelize = require('../sequelize');

exports.DatabaseTool = class DatabaseTool {
	constructor(options) {
		const { storage, host } = options;

		this.host = host;
		this.storage = storage;
		this.defaultConfigPath = DEFAULT_CONFIG_PATH;
		this.workspace = process.cwd();
		this.csvPath = path.resolve(this.workspace, './csv/data.csv');

		this.init(host, storage);
	}

	init(host, storage) {
		const [sequelize, Model] = Sequelize({
			host,
			storage: path.resolve(this.workspace, storage)
		});

		this.Model = Model;
		this.sequelize = sequelize;
	}

	// 批量导入
	async import(filePath = this.csvPath) {
		if (path.extname(filePath) !== '.csv') {
			console.log('上传的文件格式不正确，请上传.csv格式的文件');

			return Promise.reject();
		}

		try {
			const ErrorModel = this.Model.ErrorModel;

			return new Promise((resolve, reject) => {
				fs.createReadStream(filePath)
					.pipe(csv())
					.on('end', async () => {
						console.log('读取完成');

						resolve();
					})
					.on('error', async () => {
						console.log('读取.csv数据错误, 请检查数据格式');

						reject();
					})
					.on('data', async row => {
						console.log(row);
						try {
							await ErrorModel.create({
								companyName: row.company_name || '',
								modelId: row.model_id,
								fpid: row.fpid || '',
								status: 0, // 0 未处理 1：处理中 2：处理失败 3：处理成功
								uploadTime: row.upload_time
							}).then(() => {
								console.log(row.model_id, '数据保存成功');
							}).catch(error => {
								console.log('数据保存失败', error.message);
							});
						} catch (error) {
							console.log(error.message + row.model_id + row.model_version);
						}
					});

			});
		} catch (error) {
			throw new Error(error.message + 'import data error!');
		}
	}

	async reset() {
		this.init(this.host, this.storage);

		await this.sequelize.sync({ force: true });
	}
};
